/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.gwt.client.service.content;

import han.bifang.gwt.client.common.Content;
import han.bifang.gwt.client.common.EntityConstants;
import han.bifang.gwt.client.common.GwtContext;
import han.bifang.gwt.client.common.RequestObject;
import han.bifang.gwt.client.common.ResponseObject;
import han.bifang.gwt.client.common.entity.HttpBinding;
import han.bifang.gwt.client.common.entity.JmsBindingWrapper;
import han.bifang.gwt.client.common.entity.SoapBinding;
import han.bifang.gwt.client.common.entity.Version;
import han.bifang.gwt.client.common.entity.WebServicesBinding;
import han.bifang.gwt.client.common.entity.WebServicesMethodWrapper;
import han.bifang.gwt.client.common.entity.WsdlWrapper;
import han.bifang.gwt.client.common.util.StringUtils;
import han.bifang.gwt.client.communicate.BifangGWTServiceAsync;
import han.bifang.gwt.client.service.ServiceConstants;
import han.bifang.gwt.client.service.ServiceContentConstants;
import han.bifang.gwt.client.service.ServiceMessages;

import java.util.ArrayList;
import java.util.HashMap;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwt.user.client.ui.HTMLTable.ColumnFormatter;

/**
 * 
 * @Author Kent
 */
public class ModifyVersionCommContent extends Content {

	private BifangGWTServiceAsync service = null;

	private GwtContext context = null;

	private ServiceMessages cons;

	private VerticalPanel panel = null;
	private Grid wsp = null;
	private ChooseServicePanel sp = null;
	private ChooseMethodPanel mp = null;

	private Grid http = null, soap = null;
	private FlexTable webservices = null;
	private SimplePanel cp = null;
	private TextBox httpUrl = null, wsdlUrl = null,endpoint,  soapUrl;
	private ListBox soapVersion,webservicesSoapVersion ;
	private JmsPanel jms = null;
	private ListBox jmsType;
	private String flag;

	private boolean loaded = false;

	private AsyncCallback<ResponseObject> cb = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code = res.getCode();
			if (!code.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}

			ArrayList<WebServicesBinding> ret = (ArrayList<WebServicesBinding>) res
					.getResponse();

			sp = new ChooseServicePanel(cons, ret);
			wsp.setWidget(1, 0, sp);

			Button b = new Button(cons.getMethod());
			b.addClickListener(new ClickListener() {
				public void onClick(Widget sender) {
					if (!validate3())
						return;
					RequestObject req = new RequestObject();
					req
							.setAction("han.bifang.gwt.server.action.service.GetWsdlWrapperAction");
					req.setRequest(sp.getService());
					service.call(req, cb1);

				}
			});
			wsp.setWidget(2, 0, b);
			wsp.setWidget(3, 0, new HTML("&nbsp;"));
			mp = null;

		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};

	private AsyncCallback<ResponseObject> cb1 = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code = res.getCode();
			if (!code.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}

			WsdlWrapper ret = (WsdlWrapper) res.getResponse();
			endpoint.setText(ret.getWebServicesBinding().getEndpointUrl());

			mp = new ChooseMethodPanel(cons, ret);
			wsp.setWidget(3, 0, mp);

		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};

	public ModifyVersionCommContent(ServiceMessages cons,
			BifangGWTServiceAsync service, GwtContext context) {
		this.cons = cons;
		this.service = service;
		this.context = context;
		panel = new VerticalPanel();
		panel.setSpacing(5);
		panel.setWidth("100%");

		initWidget(panel);

	}

	public void onLoad() {
		if (loaded)
			return;
		else
			loaded = true;
		HTML h = new HTML(cons.communicateConfig());
		panel.add(h);

		cp = new SimplePanel();
		cp.setWidth("100%");

		http = new Grid(1, 2);
		http.setCellPadding(1);
		http.setCellSpacing(1);
		http.setBorderWidth(1);

		ColumnFormatter cf = http.getColumnFormatter();
		cf.setWidth(0, "15%");
		cf.setWidth(1, "55%");

		CellFormatter ff = http.getCellFormatter();
		ff.setStyleName(0, 0, "tablecol");

		http.setHTML(0, 0, cons.url());

		httpUrl = new TextBox();
		httpUrl.setVisibleLength(64);

		http.setWidget(0, 1, httpUrl);
		
		soap = new Grid(2, 2);
		soap.setCellPadding(1);
		soap.setCellSpacing(1);
		soap.setBorderWidth(1);

		cf = soap.getColumnFormatter();
		cf.setWidth(0, "15%");
		cf.setWidth(1, "55%");

		ff = soap.getCellFormatter();
		ff.setStyleName(0, 0, "tablecol");
		ff.setStyleName(1, 0, "tablecol");

		soap.setHTML(0, 0, cons.url());
		soap.setHTML(1, 0, cons.soapVersion());

		soapUrl = new TextBox();
		soapUrl.setVisibleLength(64);

		soap.setWidget(0, 1, soapUrl);
		
		soapVersion = new ListBox();
		soapVersion.addItem("1.1","1.1");
		soapVersion.addItem("1.2", "1.2");
		soapVersion.setSelectedIndex(0);
		
		soap.setWidget(1,1,soapVersion);

		webservices = new FlexTable();
		webservices.setCellPadding(1);
		webservices.setCellSpacing(1);
		webservices.setBorderWidth(1);

		cf = webservices.getColumnFormatter();
		cf.setWidth(0, "15%");
		cf.setWidth(1, "55%");
		cf.setWidth(1, "10%");

		FlexCellFormatter fff = webservices.getFlexCellFormatter();
		fff.setStyleName(0, 0, "tablecol");
		fff.setStyleName(1, 0, "tablecol");

		webservices.setHTML(0, 0, cons.wsdlUrl());
		webservices.setHTML(1, 0, cons.endpoint());
		webservices.setHTML(2, 0, cons.soapVersion());

		wsdlUrl = new TextBox();
		wsdlUrl.setVisibleLength(64);

		webservices.setWidget(0, 1, wsdlUrl);

		endpoint = new TextBox();
		endpoint.setVisibleLength(64);
		webservices.setWidget(1, 1, endpoint);
		
		webservicesSoapVersion = new ListBox();
		webservicesSoapVersion.addItem("1.1","1.1");
		webservicesSoapVersion.addItem("1.2", "1.2");
		webservicesSoapVersion.setSelectedIndex(0);
		webservices.setWidget(2, 1, webservicesSoapVersion);
		
		fff.setColSpan(1, 1, 2);
		fff.setColSpan(2, 1, 2);
		

		Button b1 = new Button(cons.parse());
		b1.addClickListener(new ClickListener() {

			public void onClick(Widget sender) {
				if (!validate2())
					return;
				RequestObject req = new RequestObject();
				req
						.setAction("han.bifang.gwt.server.action.service.GetAllServicesFromWSDLAction");
				req.setRequest(wsdlUrl.getText());
				service.call(req, cb);

			}

		});

		webservices.setWidget(0, 2, b1);
		wsp = new Grid(4, 1);
		wsp.setWidth("100%");
		wsp.setWidget(0, 0, webservices);

		jms = new JmsPanel(cons,null);

		HorizontalPanel hp = new HorizontalPanel();
		hp.add(new HTML(cons.protocol() + ":&nbsp;&nbsp;&nbsp;"));

		RadioButton rb0 = new RadioButton("myRadioGroup", cons.http());
		RadioButton rb1 = new RadioButton("myRadioGroup", cons.webservices());
		RadioButton rb2 = new RadioButton("myRadioGroup", cons.jms());
		RadioButton rb3 = new RadioButton("myRadioGroup", cons.soap());

		rb0.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				cp.setWidget(http);
				flag = "http";
			}
		});

		rb1.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				cp.setWidget(wsp);
				flag = "webservices";
			}
		});

		rb2.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				cp.setWidget(jms);
				flag = "jms";
			}
		});
		
		rb3.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				cp.setWidget(soap);
				flag = "soap";
			}
		});

		hp.add(rb0);
		hp.add(rb1);
		hp.add(rb2);
		hp.add(rb3);
		
		panel.add(hp);
		panel.add(cp);

		HorizontalPanel h1 = new HorizontalPanel();

		Button p = new Button(cons.previous());
		p.addClickListener(new ClickListener() {
			public void onClick(Widget send) {
				listener.onContentChanged(
						ServiceContentConstants.MODIFY_VERSION_COMM,
						ServiceContentConstants.MODIFY_VERSION_BASIC, null);

			}
		});

		Button b = new Button(cons.next());
		b.addClickListener(new ClickListener() {
			public void onClick(Widget send) {
				if (!validate1())
					return;
				Version s = (Version) context.get(ServiceConstants.VERSION);
				if (flag.equals("http")) {
					s.setBindingType(EntityConstants.BINDING_HTTP);
					HttpBinding hb = new HttpBinding();
					hb.setUrl(httpUrl.getText());
					context.put(ServiceConstants.BINDING, hb);
				} else if (flag.equals("jms")) {
					s.setBindingType(EntityConstants.BINDING_JMS);
					JmsBindingWrapper w = jms.getJmsBindingWrapper();
					if(w == null)
						return;
//					jb.setDestination(destUrl.getText());
//					jb.setFactory(jmsFac.getText());
//					jb.setPassword(passwd.getText());
//					jb.setServerUrl(serverUrl.getText());
//					jb.setType(jmsType.getItemText(jmsType.getSelectedIndex()));
//					jb.setUser(user.getText());
					context.put(ServiceConstants.BINDING, w);

				}else if(flag.equals("soap")){
					s.setBindingType(EntityConstants.BINDING_SOAP);
					SoapBinding hb = new SoapBinding();
					hb.setUrl(soapUrl.getText());
					hb.setSoapVersion(soapVersion.getValue(soapVersion.getSelectedIndex()));
					context.put(ServiceConstants.BINDING, hb);
				} 
				else if (flag.equals("webservices")) {
					s.setBindingType(EntityConstants.BINDING_WEB_SERVICES);
					WsdlWrapper w = mp.getWsdlWrapper();
					if (context.get(ServiceConstants.BINDING) != null
							&& context.get(ServiceConstants.BINDING) instanceof WsdlWrapper) {
						ArrayList newMethod = w.getMethods();
						WsdlWrapper ow = (WsdlWrapper)context.get(ServiceConstants.BINDING);
						ArrayList oMethod = ow.getMethods();
						HashMap tmp = new HashMap();
						for(int i = 0, j = oMethod.size(); i < j ; i ++){
							WebServicesMethodWrapper ws = (WebServicesMethodWrapper)oMethod.get(i);
							tmp.put(ws.getMethod().getMethodName(), ws);
						}
						for(int i = 0 , j = newMethod.size(); i < j ; i ++){
							WebServicesMethodWrapper ws = (WebServicesMethodWrapper)newMethod.get(i);
							if(tmp.get(ws.getMethod().getMethodName())!= null){
								WebServicesMethodWrapper tws = (WebServicesMethodWrapper)tmp.get(ws.getMethod().getMethodName());
								ws.setQos(tws.getQos());
							}
						}
					}

					w.getWebServicesBinding()
							.setEndpointUrl(endpoint.getText());
					w.getWebServicesBinding().setSoapVersion(webservicesSoapVersion.getValue(webservicesSoapVersion.getSelectedIndex()));
					
					context.put(ServiceConstants.BINDING, w);

				}

				context.put(ServiceConstants.VERSION, s);

				listener.onContentChanged(
						ServiceContentConstants.MODIFY_VERSION_COMM,
						ServiceContentConstants.MODIFY_VERSION_CONFIG, null);

			}
		});
		h1.add(p);
		h1.add(new HTML("&nbsp;&nbsp;"));
		h1.add(b);
		panel.add(h1);

		Version s = (Version) context.get(ServiceConstants.VERSION);
		if (!StringUtils.isEmpty(s.getBindingType())) {

			if (s.getBindingType().equals(EntityConstants.BINDING_HTTP)) {
				cp.setWidget(http);
				flag = "http";
				rb0.setChecked(true);
				HttpBinding hb = (HttpBinding) context
						.get(ServiceConstants.BINDING);
				httpUrl.setText(hb.getUrl());
			}if (s.getBindingType().equals(EntityConstants.BINDING_SOAP)) {
				cp.setWidget(soap);
				flag = "soap";
				rb3.setChecked(true);
				SoapBinding hb = (SoapBinding) context
						.get(ServiceConstants.BINDING);
				soapUrl.setText(hb.getUrl());
				if(hb.getSoapVersion().equals("1.2"))
					soapVersion.setSelectedIndex(1);
				else{
					soapVersion.setSelectedIndex(0);
				}
			}  
			else if (s.getBindingType().equals(EntityConstants.BINDING_WEB_SERVICES)) {
				cp.setWidget(wsp);
				flag = "webservices";
				rb1.setChecked(true);
				WsdlWrapper hb = (WsdlWrapper) context
						.get(ServiceConstants.BINDING);

				wsdlUrl.setText(hb.getWebServicesBinding().getWsdlUrl());
				if(hb.getWebServicesBinding().getSoapVersion().equals("1.2"))
					webservicesSoapVersion.setSelectedIndex(1);
				else{
					webservicesSoapVersion.setSelectedIndex(0);
				}
				// httpUrl.setText(hb.getUrl());
			} else if (s.getBindingType().equals(EntityConstants.BINDING_JMS)) {
				cp.setWidget(jms);
				flag = "jms";
				rb2.setChecked(true);
				JmsBindingWrapper hb = (JmsBindingWrapper) context
						.get(ServiceConstants.BINDING);
				jms = new JmsPanel(cons, hb);
				cp.setWidget(jms);
//				serverUrl.setText(hb.getServerUrl());
//				jmsFac.setText(hb.getFactory());
//				destUrl.setText(hb.getDestination());
//				if (hb.getType().equals(EntityConstants.JMS_TYPE_QUEUE)) {
//					jmsType.setSelectedIndex(0);
//				} else {
//					jmsType.setSelectedIndex(1);
//				}
//				user.setText(hb.getUser());
//				passwd.setText(hb.getPassword());
			}
		} else {
			//Window.alert("test");
			rb0.setChecked(true);
			cp.setWidget(http);
			flag = "http";
		}

	}

	public void onUnLoad() {
		// Window.alert("unload");
	}

	private boolean validate1() {
		if (flag.equals("http")) {
			if (!StringUtils.checkLenght(httpUrl.getText(), 1, 1024)) {
				Window.alert(cons.lengthError(cons.url(), "1", "1024"));
				return false;
			}
		} else if (flag.equals("jms")) {
			
		} else if (flag.equals("webservices")) {
			if (!StringUtils.checkLenght(wsdlUrl.getText(), 1, 1024)) {
				Window.alert(cons.lengthError(cons.wsdlUrl(), "1", "1024"));
				return false;
			}

			if (sp == null) {
				Window.alert(cons.mustParseError());
				return false;
			}
			if (mp == null) {
				Window.alert(cons.mustGetMethodsError());
				return false;
			}
			if (mp.getWsdlWrapper().getMethods().size() == 0) {
				Window.alert(cons.mustChooseMethodError());
				return false;
			}
			if (!StringUtils.checkLenght(endpoint.getText(), 1, 1024)) {
				Window.alert(cons.lengthError(cons.endpoint(), "1", "1024"));
				return false;
			}

		}
		return true;

	}

	private boolean validate2() {
		if (!StringUtils.checkLenght(wsdlUrl.getText(), 1, 1024)) {
			Window.alert(cons.lengthError(cons.wsdlUrl(), "1", "1024"));
			return false;
		}

		return true;

	}

	private boolean validate3() {
		if (sp.getService() == null) {
			Window.alert(cons.mustChooseServiceError());
			return false;
		}

		return true;

	}

}
